package com.arloesol.android.jimmobileblue;


import java.lang.reflect.Method;

import android.content.Context;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class Util {

  final static public String StringBetween(String text, String before, String after) {
    if (text.indexOf(before) == -1) {
      return ("");
    }
    ;
    if (text.indexOf(after) == -1) {
      return ("");
    }
    ;
    return text.substring(text.indexOf(before) + before.length(), text.indexOf(after));
  }

  @SuppressWarnings("rawtypes")
  final static public void SetDataConnection(Context context, boolean enableIt) {
  // Todo : once an official way exists to stop data connection use it !!
  // in the mean-time this works but it uses a private method from the android core
    boolean isEnabled;
    Method dataConnSwitchmethod = null;
    Class telephonyManagerClass;
    Object ITelephonyStub;
    Class ITelephonyClass;

    final TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    if (telephonyManager.getDataState() == TelephonyManager.DATA_CONNECTED) {
      isEnabled = true;
    } else {
      isEnabled = false;
    }
    try {
      telephonyManagerClass = Class.forName(telephonyManager.getClass().getName());
      Method getITelephonyMethod = telephonyManagerClass.getDeclaredMethod("getITelephony");
      getITelephonyMethod.setAccessible(true);
      ITelephonyStub = getITelephonyMethod.invoke(telephonyManager);
      ITelephonyClass = Class.forName(ITelephonyStub.getClass().getName());

      if (isEnabled & !enableIt) {
        dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("disableDataConnectivity");
      } else if (!isEnabled && enableIt) {
        dataConnSwitchmethod = ITelephonyClass.getDeclaredMethod("enableDataConnectivity");
      }
      dataConnSwitchmethod.setAccessible(true);
      dataConnSwitchmethod.invoke(ITelephonyStub);
    } catch (Exception e) {
      Toast.makeText(context, "Exception " + e.toString(), Toast.LENGTH_LONG).show();
      if (enableIt) {
        Toast.makeText(context, "Can't Enable Data Connection", Toast.LENGTH_LONG).show();
      } else {
        Toast.makeText(context, "Can't Stop Data Connection", Toast.LENGTH_LONG).show();
      }
    }
  }
}
